<template>
  <div class="confirm-order-container">
    <!-- 头部 -->
    <div class="order-header">
      <div class="header-content">
        <i class="el-icon-notebook-2"></i>
        <h1>确认订单</h1>
        <div class="header-divider"></div>
      </div>
    </div>
    <!-- 头部END -->

    <!-- 主要内容容器 -->
    <div class="order-content">
      <!-- 选择地址 -->
      <div class="address-section">
        <div class="section-title">
          <i class="el-icon-location-outline"></i>
          <span>收货地址</span>
        </div>
        <div class="address-list">
          <div
            class="address-card"
            v-for="item in addressList"
            :key="item.id"
            :class="item.id == confirmAddress ? 'active' : ''"
            @click="chooseAddress(item.id)"
          >
            <div class="address-header">
              <span class="name">{{item.name}}</span>
              <span class="phone">{{item.phoneNum}}</span>
              <i v-if="item.id == confirmAddress" class="el-icon-edit edit-icon" @click.stop="editAddress(item)"></i>
            </div>
            <p class="address-detail">{{item.content}}</p>
            <div v-if="item.id == confirmAddress" class="selected-tag">
              <i class="el-icon-check"></i> 已选
            </div>
          </div>
          
          <div class="add-address-card" @click="addAddress">
            <i class="el-icon-circle-plus"></i>
            <p>添加新地址</p>
          </div>
        </div>
      </div>
      <!-- 选择地址END -->

      <!-- 商品列表 -->
      <div class="books-section">
        <div class="section-title">
          <i class="el-icon-reading"></i>
          <span>购买图书</span>
        </div>
        <div class="book-list">
          <div class="book-item" v-for="item in getCheckGoods" :key="item.id">
            <img :src="$target + item.productImg" class="book-cover" />
            <div class="book-info">
              <h3 class="book-title">{{item.productName}}</h3>
              <p class="book-author">作者：{{item.author || '未知'}}</p>
            </div>
            <div class="book-price">
              <span class="price">{{item.price}}元 × {{item.num}}</span>
              <span class="total">{{item.price * item.num}}元</span>
            </div>
          </div>
        </div>
      </div>
      <!-- 商品列表END -->

      <!-- 配送和发票 -->
      <div class="info-section">
        <div class="info-item">
          <div class="section-title">
            <i class="el-icon-truck"></i>
            <span>配送方式</span>
          </div>
          <p class="info-content">快递配送 · 包邮</p>
        </div>
        
        <div class="info-item">
          <div class="section-title">
            <i class="el-icon-document"></i>
            <span>发票信息</span>
          </div>
          <p class="info-content">电子发票 · 个人 · 商品明细</p>
        </div>
      </div>
      <!-- 配送和发票END -->

      <!-- 结算信息 -->
      <div class="summary-section">
        <div class="summary-item">
          <span>商品件数：</span>
          <span>{{getCheckNum}}件</span>
        </div>
        <div class="summary-item">
          <span>商品总价：</span>
          <span>{{getTotalPrice}}元</span>
        </div>
        <div class="summary-item">
          <span>优惠折扣：</span>
          <span>-0元</span>
        </div>
        <div class="summary-item">
          <span>运费：</span>
          <span>0元</span>
        </div>
        <div class="summary-total">
          <span>应付总额：</span>
          <span class="total-price">{{getTotalPrice}}元</span>
        </div>
      </div>
      <!-- 结算信息END -->

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button class="back-btn" @click="$router.push('/shoppingCart')">
          <i class="el-icon-arrow-left"></i> 返回购物车
        </el-button>
        <el-button type="primary" class="submit-btn" @click="addOrder">
          <i class="el-icon-sell"></i> 提交订单
        </el-button>
      </div>
      <!-- 操作按钮END -->
    </div>
    <!-- 主要内容容器END -->

    <!-- 地址编辑对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="address" :rules="rules" ref="ruleForm" label-width="80px">
        <el-form-item label="收件人" prop="name">
          <el-input
            prefix-icon="el-icon-user"
            v-model="address.name"
            placeholder="请输入收件人姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNum">
          <el-input
            prefix-icon="el-icon-phone"
            v-model="address.phoneNum"
            placeholder="请输入手机号码"
          ></el-input>
        </el-form-item>
        <el-form-item label="详细地址" prop="content">
          <el-input
            type="textarea"
            :rows="3"
            v-model="address.content"
            placeholder="请输入详细地址信息"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogSure">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters, mapActions } from "vuex";

export default {
  name: "ConfirmOrder",
  data() {
    let validatePhoneNum = ( rule, value, callback ) => {
      if (value == '') {
        return callback(new Error('请输入手机号'))
      } else {
        if (!(/^1[34578]\d{9}$/.test(value))) {
          return callback(new Error('请输入正确的手机号'))
        } else {
          if (value.length != 11) {
            return callback(new Error('请输入正确的手机号'))
          } else {
            return callback()
          }
        }
      }
    }
    return {
      title: '新增地址',
      dialogVisible: false,
      address: {
        name: '',
        phoneNum: '',
        content: '',
        id: ''
      },
      rules: {
        name: [{ required: true, message: '请输入收件人', trigger: 'blur' }],
        phoneNum: [{ validator: validatePhoneNum, trigger: "blur" }],
        content: [{ required: true, message: '请输入收货地址', trigger: 'blur' }],
      },
      confirmAddress: '',
      addressList: []
    };
  },
  created() {
    if (this.getCheckNum < 1) {
      this.notifyError("请勾选图书后再结算");
      this.$router.push({ path: "/shoppingCart" });
    }
    this.getAddressList()
  },
  computed: {
    ...mapGetters(["getCheckNum", "getTotalPrice", "getCheckGoods"])
  },
  methods: {
    ...mapActions(["deleteShoppingCart"]),
    chooseAddress(id) {
      this.confirmAddress = id
    },
    getAddressList() {
      this.$axios.post('/api/user/address/getList', {
        user_id: JSON.parse(localStorage.getItem('user')).user_id
      })
        .then(res => {
          if (res.data.code == '001') {
            this.addressList = res.data.data
            if (this.addressList.length > 0 && !this.confirmAddress) {
              this.confirmAddress = this.addressList[0].id
            }
          } else {
            this.notifyError(res.data.msg)
          }
        })
        .catch(err =>{
          this.notifyError(err.message)
        })
    },
    dialogSure() {
      this.$refs["ruleForm"].validate(valid => {
        if (valid) {
          if (this.title == '新增地址') {
            this.$axios
              .post("/api/user/addresss/addAddress", {
                name: this.address.name,
                phoneNum: this.address.phoneNum,
                content: this.address.content,
                user_id: JSON.parse(localStorage.getItem('user')).user_id
              })
              .then(res => {
                if (res.data.code == '001') {
                  this.getAddressList()
                  this.dialogVisible = false
                  this.address = { name: '', phoneNum: '', content: '', id: '' }
                  this.notifySucceed(res.data.msg);
                } else {
                  this.notifyError(res.data.msg);
                }
              })
              .catch(err => {
                this.notifyError(err.message);
              })
          } else if (this.title == '编辑地址') {
            this.$axios
              .post("/api/user/addresss/updateAddress", {
                name: this.address.name,
                phoneNum: this.address.phoneNum,
                content: this.address.content,
                id: this.address.id
              })
              .then(res => {
                if (res.data.code == '001') {
                  this.getAddressList()
                  this.dialogVisible = false
                  this.address = { name: '', phoneNum: '', content: '', id: '' }
                  this.notifySucceed(res.data.msg);
                } else {
                  this.notifyError(res.data.msg);
                }
              })
              .catch(err => {
                this.notifyError(err.message);
              })
          }
        }
      })
    },
    addAddress() {
      this.title = '新增地址'
      this.address = { name: '', phoneNum: '', content: '', id: '' }
      this.dialogVisible = true
    },
    editAddress(val) {
      this.title = '编辑地址'
      this.address = {
        id: val.id,
        name: val.name,
        phoneNum: val.phoneNum,
        content: val.content
      }
      this.dialogVisible = true
    },
    addOrder() {
      if (!this.confirmAddress) {
        this.notifyError('请选择收货地址');
        return
      }
      this.$axios
        .post("/api/user/order/addOrder", {
          user_id: this.$store.getters.getUser.user_id,
          products: this.getCheckGoods,
          status: '1',
          addressId: this.confirmAddress
        })
        .then(res => {
          let products = this.getCheckGoods;
          switch (res.data.code) {
            case "001":
              for (let i = 0; i < products.length; i++) {
                const temp = products[i];
                this.deleteShoppingCart(temp.id);
              }
              this.notifySucceed(res.data.msg);
              this.$router.push({ path: "/order" });
              break;
            default:
              this.notifyError(res.data.msg);
          }
        })
        .catch(err => {
          return Promise.reject(err);
        });
    }
  }
};
</script>

<style>
/* 基础样式 */
.confirm-order-container {
  background-color: #f8f9fa;
  min-height: 100vh;
  padding-bottom: 40px;
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", Arial, sans-serif;
}

/* 头部样式 */
.order-header {
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 20px 0;
}

.header-content {
  width: 1200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
}

.header-content i {
  font-size: 36px;
  color: #409EFF;
  margin-right: 15px;
}

.header-content h1 {
  font-size: 24px;
  color: #333;
  font-weight: 500;
  margin: 0;
}

.header-divider {
  flex-grow: 1;
  border-bottom: 1px dashed #e0e0e0;
  margin-left: 20px;
}

/* 主要内容容器 */
.order-content {
  width: 1200px;
  margin: 30px auto 0;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  padding: 30px;
}

/* 通用标题样式 */
.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.section-title i {
  font-size: 20px;
  color: #409EFF;
  margin-right: 10px;
}

.section-title span {
  font-size: 18px;
  color: #333;
  font-weight: 500;
}

/* 地址部分样式 */
.address-section {
  margin-bottom: 30px;
}

.address-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.address-card {
  width: calc(33.333% - 10px);
  padding: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
  background-color: #fafafa;
}

.address-card:hover {
  border-color: #c0c4cc;
}

.address-card.active {
  border-color: #409EFF;
  background-color: #f0f7ff;
}

.address-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.address-header .name {
  font-size: 16px;
  font-weight: 500;
  margin-right: 15px;
}

.address-header .phone {
  color: #666;
}

.address-header .edit-icon {
  margin-left: auto;
  color: #999;
  font-size: 18px;
}

.address-header .edit-icon:hover {
  color: #409EFF;
}

.address-detail {
  color: #666;
  line-height: 1.6;
}

.selected-tag {
  position: absolute;
  right: 0;
  top: 0;
  background-color: #409EFF;
  color: white;
  padding: 2px 8px;
  border-bottom-left-radius: 6px;
  font-size: 12px;
}

.selected-tag i {
  margin-right: 3px;
}

.add-address-card {
  width: calc(33.333% - 10px);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px;
  border: 1px dashed #e0e0e0;
  border-radius: 6px;
  cursor: pointer;
  color: #999;
  transition: all 0.3s;
}

.add-address-card i {
  font-size: 24px;
  margin-bottom: 10px;
}

.add-address-card:hover {
  border-color: #409EFF;
  color: #409EFF;
}

/* 图书列表样式 */
.books-section {
  margin-bottom: 30px;
}

.book-list {
  border: 1px solid #e0e0e0;
  border-radius: 6px;
}

.book-item {
  display: flex;
  align-items: center;
  padding: 20px;
  border-bottom: 1px dashed #e0e0e0;
}

.book-item:last-child {
  border-bottom: none;
}

.book-cover {
  width: 60px;
  height: 80px;
  object-fit: cover;
  margin-right: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.book-info {
  flex-grow: 1;
}

.book-title {
  font-size: 16px;
  margin: 0 0 8px 0;
  color: #333;
}

.book-author {
  font-size: 14px;
  color: #999;
  margin: 0;
}

.book-price {
  text-align: right;
  min-width: 150px;
}

.book-price .price {
  display: block;
  color: #666;
  margin-bottom: 5px;
}

.book-price .total {
  font-weight: 500;
  color: #ff6700;
}

/* 配送和发票信息样式 */
.info-section {
  display: flex;
  margin-bottom: 30px;
}

.info-item {
  flex: 1;
}

.info-item:first-child {
  margin-right: 20px;
}

.info-content {
  padding: 15px;
  background-color: #fafafa;
  border-radius: 6px;
  color: #666;
}

/* 结算信息样式 */
.summary-section {
  background-color: #fafafa;
  padding: 20px;
  border-radius: 6px;
  margin-bottom: 30px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  color: #666;
}

.summary-item:last-child {
  margin-bottom: 0;
}

.summary-total {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px dashed #e0e0e0;
  font-size: 18px;
  font-weight: 500;
}

.summary-total .total-price {
  color: #ff6700;
  font-size: 20px;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  justify-content: flex-end;
}

.action-buttons .back-btn {
  margin-right: 20px;
}

.action-buttons .submit-btn {
  padding: 12px 30px;
  font-size: 16px;
}

/* 对话框样式优化 */
.el-dialog {
  border-radius: 8px !important;
}

.el-dialog__header {
  border-bottom: 1px solid #f0f0f0;
  padding: 15px 20px;
}

.el-dialog__title {
  font-weight: 500;
}

.el-dialog__body {
  padding: 20px 30px;
}

.el-dialog__footer {
  border-top: 1px solid #f0f0f0;
  padding: 15px 20px;
  text-align: right;
}
</style>